// Created by wangliang on 2025/6/27.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_demo/base/base_view_model.dart';
import 'package:flutter_app_demo/pages/live/settings/live_audo_settings.dart';
import 'package:flutter_app_demo/utils/logger.dart';
import 'package:live_flutter_plugin/manager/tx_audio_effect_manager.dart';
import 'package:live_flutter_plugin/manager/tx_beauty_manager.dart';
import 'package:live_flutter_plugin/manager/tx_device_manager.dart';
import 'package:live_flutter_plugin/v2_tx_live_code.dart';
import 'package:live_flutter_plugin/v2_tx_live_def.dart';
import 'package:live_flutter_plugin/v2_tx_live_pusher.dart';
import 'package:live_flutter_plugin/v2_tx_live_pusher_observer.dart';

class LiveCameraPushPageViewModel extends BaseViewModel {
  V2TXLivePusher? _livePusher;

  /// 音频数据
  final LiveAudioSettings _audioSettings = LiveAudioSettings();

  V2TXLiveAudioQuality _audioQuality = V2TXLiveAudioQuality.v2TXLiveAudioQualityDefault;

  LiveAudioSettings get audioSettings => _audioSettings;

  V2TXLiveVideoResolution _resolution = V2TXLiveVideoResolution.v2TXLiveVideoResolution640x480;

  /// 旋转角度
  V2TXLiveRotation _liveRotation = V2TXLiveRotation.v2TXLiveRotation0;

  /// 摄像头
  V2TXLiveMirrorType _liveMirrorType = V2TXLiveMirrorType.v2TXLiveMirrorTypeAuto;

  bool _isEnableBeauty = false;

  /// 音频设置
  bool _microphoneEnable = true;
  TXDeviceManager? _txDeviceManager;
  TXBeautyManager? _txBeautyManager;
  TXAudioEffectManager? _txAudioManager;

  int? localViewId;

  @override
  void initState() {
    super.initState();
    initLive();
  }

  @override
  void dispose() {
    super.dispose();
    _livePusher?.removeListener(onPusherObserver);
    _livePusher?.stopMicrophone();
    _livePusher?.stopCamera();
    _livePusher?.stopPush();
    _livePusher?.destroy();
  }

  initLive() async {
    await initPlatformState();
    // 获取设备管理模块
    _txDeviceManager = _livePusher?.getDeviceManager();
    // 获取美颜管理对象
    _txBeautyManager = _livePusher?.getBeautyManager();
    // 获取音效管理类 TXAudioEffectManager
    _txAudioManager = _livePusher?.getAudioEffectManager();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    _livePusher = await V2TXLivePusher.create(V2TXLiveMode.v2TXLiveModeRTMP);
    _livePusher?.addListener(onPusherObserver);
    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    safeBuildView();
    Log.d("CreatePusher result is ${_livePusher?.status}");
  }

  onPusherObserver(V2TXLivePusherListenerType type, param) {
    Log.d("==pusher listener type= ${type.toString()}");
    Log.d("==pusher listener param= $param");

    if (type == V2TXLivePusherListenerType.onMusicObserverStart) {
      _audioSettings.isPlaying = true;
      safeBuildView();
    }
    if (type == V2TXLivePusherListenerType.onMusicObserverPlayProgress) {}
    if (type == V2TXLivePusherListenerType.onMusicObserverComplete) {
      _audioSettings.isPlaying = false;
      safeBuildView();
    }
  }

  startPush() async {
    if (_livePusher == null) {
      return;
    }
    await _livePusher?.setRenderMirror(_liveMirrorType);
    var videoEncoderParam = V2TXLiveVideoEncoderParam();
    videoEncoderParam.videoResolution = _resolution;
    videoEncoderParam.videoResolutionMode = V2TXLiveVideoResolutionMode.v2TXLiveVideoResolutionModePortrait;
    await _livePusher?.setVideoQuality(videoEncoderParam);
    await _livePusher?.setAudioQuality(_audioQuality);

    if (localViewId != null) {
      var code = await _livePusher?.setRenderViewID(localViewId!);
      if (code != V2TXLIVE_OK) {
        showErrordDialog("StartPush error： please check remoteView load");
        return;
      }
    }
    var cameraCode = await _livePusher?.startCamera(true);
    if (cameraCode == null || cameraCode != V2TXLIVE_OK) {
      debugPrint("cameraCode: $cameraCode");
      showErrordDialog("Camera push error：please check Camera system auth.");
      return;
    }
    // var url = URLUtils.generateTRTCPushUrl(widget.streamId, null);
    // if (widget.liveMode == V2TXLiveMode.v2TXLiveModeRTMP) {
    //   url = URLUtils.generateRtmpPushUrl(widget.streamId);
    // }
    var url =
        "rtmp://215665.push.tlivecloud.com/live/ruixue1?txSecret=731eb6aae8c7407d8094235b76557d21&txTime=685A55E7";
    debugPrint("推流地址： $url");
    var pushCode = await _livePusher?.startPush(url);
    debugPrint("推流结果： $pushCode");
    if (pushCode == null || pushCode != V2TXLIVE_OK) {
      showErrordDialog("Camera push error：($pushCode) please check push url or LicenceURL");
      return;
    }
    if (_microphoneEnable) {
      await _livePusher?.startMicrophone();
    }
    var isFrontCamera = await _txDeviceManager?.isFrontCamera();
    debugPrint("current device isFrontCamera: $isFrontCamera");
  }

  stopPush() async {
    await _livePusher?.stopMicrophone();
    await _livePusher?.stopCamera();
    await _livePusher?.stopPush();
  }

  // sdk出错信查看
  Future<bool?> showErrordDialog(errorMsg) {
    return showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return CupertinoAlertDialog(
          title: const Text("Alert"),
          content: Text(errorMsg),
          actions: <Widget>[
            TextButton(
              child: const Text("OK"),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
          ],
        );
      },
    );
  }
}
